package javagame;

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;

public class Picture {
    private BufferedImage[] images;
    private int width, height;
    
    // Creates a picture. resource is the image file to read, w/h = width/height of one frame.
    // If it is a picturesheet it'll read each frame into an array.
    // If TRANS is true then the upper-left pixel is the transparent color.
    public Picture(URL resource, int w, int h, boolean trans) {
        try {
            BufferedImage src = ImageIO.read(resource);
            Color transcol = new Color(src.getRGB(0, 0), false);
            if(src.getWidth() % w == 0 && src.getHeight() % h == 0) {
                int rows = src.getHeight() / h;
                int cols = src.getWidth() / w;
                // Fill the array of frames. If it's a picturesheet go left to right, top to bottom like reading.
                images = new BufferedImage[cols * rows];
                for(int y = 0; y < rows; y++) {
                    for(int x = 0; x < cols; x++) {
                        images[x + x * y] = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                        Graphics2D g = images[x + x * y].createGraphics();
                        g.drawImage(src, 0, 0, w, h, x * w, y * h, x * w + w, y * h + h, null);
                        if(trans) {
                            for(int fy = 0; fy < images[x + x * y].getHeight(); fy++) {
                                for(int fx = 0; fx < images[x + x * y].getWidth(); fx++) {
                                    Color mc = new Color(images[x + x * y].getRGB(fx, fy), false);
                                    if(mc.equals(transcol)) {
                                        images[x + x * y].setRGB(fx, fy, 0);
                                    }
                                }
                            }
                        }
                    }
                }
                width = w;
                height = h;
            } else {
                System.out.println("Image dimension specification error.");
            }
        } catch(FileNotFoundException e) {
            System.out.println("Sprite file not found error.");
        } catch(IOException e) {
            System.out.println("Error loading picture.");
        }
    }
    
    public int getWidth() {
        return width;
    }
    
    public int getHeight() {
        return height;
    }
    
    public int getFrameCount() {
        return images.length;
    }
    
    public BufferedImage getFrame(int f) {
        if(f >= 0 && f < images.length) {
            return images[f];
        } else {
            return null;
        }
    }
}
